import os
import json

from django.shortcuts import render
from django.http import JsonResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.contrib import auth
from django.conf import settings

from .models import TodoList

BASE_DIR = settings.BASE_DIR
CORS = 'http://localhost:3000'

@csrf_exempt
def index(request):
    dic = {'code': 0, 'msg': '', 'data':None}
    if not request.user.is_authenticated:
        dic['code'] = -5
        dic['msg'] = 'permission denied, user not logged in'
    elif request.method == 'GET':
        data_list = []
        for item in TodoList.objects.filter(user=request.user):
            data_list.append({'id':item.uid, 'title': item.title, 'completed': item.completed})
        dic['data'] = data_list
    elif request.method == 'POST':
        esc_delete = request.POST.get('delete')
        esc_id = request.POST.get('id')
        if (esc_id is None):
            dic['code'] = -1
            dic['msg'] = 'id missing'
        if(esc_delete == '1'):
            query_set = TodoList.objects.filter(uid=esc_id, user=request.user)
            if(len(query_set) == 0):
                dic['code'] = -4
                dic['msg'] = 'todolist with request id not exists in database'
            else:
                query_set.delete()
        else:
            esc_title = request.POST.get('title')
            esc_completed = request.POST.get('completed')
            if (esc_title is None):
                dic['code'] = -2
                dic['msg'] = 'title missing'
            elif (esc_completed is None):
                dic['code'] = -3
                dic['msg'] = 'completed missing'
            else:
                query_set = TodoList.objects.filter(uid=esc_id, user=request.user)
                if(len(query_set) == 0):
                    todolist = TodoList(title = esc_title,
                            completed = (esc_completed == '1'),
                            uid = esc_id,
                            user=request.user
                            )
                    todolist.save()
                else:
                    todolist = TodoList.objects.get(uid=esc_id, user=request.user)
                    todolist.title = esc_title
                    todolist.completed = (esc_completed == '1')
                    todolist.save()
    else:
        return HttpResponseBadRequest()
    response = JsonResponse(dic) # pass a Python dic
    response['Access-Control-Allow-Origin'] = CORS
    response['Access-Control-Allow-Credentials'] = 'true'
    return response

@csrf_exempt
def login(request):
    dic = {'code': 0, 'msg': '', 'data':None}
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = auth.authenticate(request, username=username, password=password)
        if user is None:
            dic['code'] = -6
            dic['msg'] = 'login failed'
        else:
            auth.login(request, user)
    else:
        return HttpResponseBadRequest()
    response = JsonResponse(dic) # pass a Python dic
    response['Access-Control-Allow-Origin'] = CORS
    response['Access-Control-Allow-Credentials'] = 'true'
    return response

@csrf_exempt    
def logout(request):
    dic = {'code': 0, 'msg': '', 'data':None}
    if request.user.is_authenticated:
            auth.logout(request)
    else:
        return HttpResponseBadRequest()
    response = JsonResponse(dic) # pass a Python dic
    response['Access-Control-Allow-Origin'] = CORS
    response['Access-Control-Allow-Credentials'] = 'true'
    return response

@csrf_exempt
def index_file(request):
    dic = {'code': 0, 'msg': '', 'data': None}
    if not request.user.is_authenticated:
        dic['code'] = -5
        dic['msg'] = 'permission denied, user not logged in'
    elif request.method == 'GET':
        fileName = os.path.join(BASE_DIR, 'user', request.user.username + '.json')
        if(os.path.exists(fileName)):
            dic['data'] = open(fileName).read()
        else:
            dic['data'] = '[]'
    elif request.method == 'POST':
        shouldContinue = True
        try:
            data = request.body.decode('utf-8')
            json_data = json.loads(data)
        except Exception as e:
            dic['code'] = -7
            dic['msg'] = 'json format corrupted'
            shouldContinue = False
        saved_json_data = []
        if(shouldContinue):
            for item in json_data:
                try:
                    _id, _text, _completed = item['id'], item['text'], item['completed']
                except Exception as e:
                    dic['code'] = -8
                    dic['msg'] = 'json format missing key'
                    continue
                saved_json_data.append({'id': _id, 'text': _text, 'completed': _completed})
            fileName = os.path.join(BASE_DIR, 'user', request.user.username + '.json')
            with open(fileName, 'w') as f:
                f.write(json.dumps(saved_json_data))
    response = JsonResponse(dic)  
    response['Access-Control-Allow-Origin'] = CORS
    response['Access-Control-Allow-Credentials'] = 'true'
    return response  







